package com.project.controller.web;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.project.entity.User;
import com.project.myBeans.R;
import com.project.myBeans.ResponseBean;
import com.project.service.MessageService;
import com.project.service.UserService;
import com.project.service.base.BaseService;
import com.project.service.base.Captcha.CaptchaService;
import com.project.service.base.CrpData.CrypDataHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author: TateBrown
 * @date: 2018/5/27 14:06
 * @param:
 * @return:
 */
@EnableAutoConfiguration //自动载入应用程序所需的所有Bean
@RestController //@Controller与@ResponseBody的合并
@RequestMapping(value = "/message")
@Api(description = "消息控制",value = "message")
public class MessageController extends BaseService{
    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    @Autowired
    private CrypDataHelper crypDataHelper;
    /**
     * TateBrown 2018年5月27日
     *
     * @param request
     * @return
     */
    @ApiOperation("短信通知：提醒发货SMS_87625008")
    @GetMapping("/smail/sendMailCode")
    public ResponseBean sendEmail(HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();

        String mailCode="";
        String email = "";
        String username = request.getParameter("username");
        String universityid = request.getParameter("universityid");
        try {
            if(!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(universityid)){
                User user = userService.findOneByUserNameAndUniversityId(username,Integer.parseInt(universityid));
                if(user == null){
                    responseBean.setSuccess(false);
                    responseBean.setMsg("此用户不存在");
                    return responseBean;
                }
                else if(StringUtils.isEmpty(user.getEmail())){
                    responseBean.setMsg("此用户尚未绑定邮箱");
                    responseBean.setSuccess(false);
                    return responseBean;
                }
                else{
                    email = crypDataHelper.decEmail(user.getEmail());
                    responseBean.setMsg("验证码已发送到"+email.split("@")[0].substring(0,3)+"******@"+email.split("@")[1]+"的邮箱");
                }

                mailCode = getSmsCode();
                JavaMailSenderImpl mailSender = getMailSender();
                //发送HTML邮件
                mailSender.setDefaultEncoding("UTF-8");
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
                mimeMessageHelper.setText("<font color='red'>您的验证码为"+mailCode+",此验证码仅用于实践管理系统,5分钟内有效。如非本人操作请忽略。</font>",true);
                mimeMessageHelper.setFrom(mailSender.getUsername());
                mimeMessageHelper.setTo(email);
                mimeMessageHelper.setSubject("实践管理系统邮箱验证");
                log.info(mailCode);
                // 发送邮件
                mailSender.send(mimeMessage);
                //将邮箱验证码加入cache
                captchaService.addCaptcha(user.getId().toString(),mailCode);
            }
            else{
                responseBean.setMsg("用户名不可为空");
                responseBean.setSuccess(false);
                return responseBean;
            }

        }
        catch(Exception e) {
            e.printStackTrace();
            responseBean.setMsg("请重新获取");
            responseBean.setSuccess(false);
        }

        return responseBean;
    }
    /**
     * TateBrown 2018年5月27日
     *
     * @param user
     * @return
     */
    @ApiOperation("短信通知")
    @PostMapping("/sms/sendSmsCode")
    public Object sendSmsCode(@RequestBody User user){
        System.out.println("user=="+ JSON.toJSONString(user));

        String username = user.getUsername();
        Integer universityid = user.getUniversityid();
        String mobile="";
        String verifyCode="";
        try {
            if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getUniversityid().toString())){ //判断用户名和大学id是否为空
                throw new Exception("用户名或大学不可为空");
            }else{ //用于WEB端找回密码等场合，先根据username找到绑定的手机号
                User user1 = userService.findOneByUserNameAndUniversityId(username,universityid);
                if(user1==null){
                    responseBean.setMsg("此用户不存在");
                    responseBean.setSuccess(false);
                    return responseBean;
                }else if(StringUtils.isEmpty(user1.getMobilephone())){
                    responseBean.setSuccess(false);
                    responseBean.setMsg("此用户尚未绑定手机号");
                    return responseBean;
                }else{
                    mobile=crypDataHelper.decMobilePhone(user1.getMobilephone());

                    verifyCode=getSmsCode();//生成验证码
                    String smsTemplate=configParameters.getSmsTemplateRecoverLoginPassword();; //根据type获取不同的模板

                    //阿里大鱼
//                    messageService.sendSmsCode(mobile,verifyCode,smsTemplate);
                    //将短信验证码加入cache
                    captchaService.addCaptcha(user1.getId().toString(),verifyCode);

                    responseBean.setMsg("验证码已发送到尾号为"+mobile.substring(mobile.length()-4,mobile.length())+"的手机");
                    responseBean.setSuccess(true);
                    log.info("验证码==="+verifyCode);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setMsg("获取验证码失败，请重新获取");
            responseBean.setSuccess(false);

        }
        return responseBean;
    }
}
